package com.zwb.demo.easyweb.modules.database.service.impl;

import com.zwb.demo.easyweb.common.entity.response.CommonCode;
import com.zwb.demo.easyweb.common.entity.response.ResponseResult;
import com.zwb.demo.easyweb.core.exception.ExceptionCast;
import com.zwb.demo.easyweb.core.utils.ConvertUtils;
import com.zwb.demo.easyweb.modules.database.entity.DatabaseColumnPO;
import com.zwb.demo.easyweb.modules.database.repository.DatabaseColumnPORepository;
import com.zwb.demo.easyweb.modules.database.service.DatabaseColumnService;
import com.zwb.demo.easyweb.modules.database.vo.DatabaseColumnVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DatabaseColumnServiceImpl implements DatabaseColumnService {

    private final DatabaseColumnPORepository databaseColumnPORepository;

    @Autowired
    public DatabaseColumnServiceImpl(DatabaseColumnPORepository databaseColumnPORepository) {
        this.databaseColumnPORepository = databaseColumnPORepository;
    }

    @Override
    public ResponseResult findAllColumnByTableId(String uuid) {
        if (StringUtils.isBlank(uuid)){
            ExceptionCast.cast(CommonCode.ILLEGAL_PARAM);
        }
        List<DatabaseColumnPO> allPo = databaseColumnPORepository.findAllByTableId(uuid);
        List<DatabaseColumnVO> allVo = ConvertUtils.convertList(allPo, DatabaseColumnVO.class);
        return ResponseResult.ok().body(allVo);
    }

    public ResponseResult addOrUpdateOne(DatabaseColumnVO vo) {
        if (StringUtils.isNotBlank(vo.getId())){
            Optional<DatabaseColumnPO> optional = databaseColumnPORepository.findById(vo.getId());
            if (!optional.isPresent()){
                ExceptionCast.cast(CommonCode.ID_NO_EXITS);
            }
            DatabaseColumnPO po = optional.get();
            BeanUtils.copyProperties(vo, po);
            databaseColumnPORepository.save(po);
        }else {
            DatabaseColumnPO po = ConvertUtils.convertObject(vo, DatabaseColumnPO.class);
            databaseColumnPORepository.save(po);
        }
        return ResponseResult.ok();
    }
}
